<template>
  <div class="tag-selector">
    <!-- 搜索框 -->
    <div class="relative mb-4">
      <Search class="absolute left-3 top-1/2 transform -translate-y-1/2 text-electric-500 w-4 h-4" />
      <input
        v-model="searchQuery"
        type="text"
        placeholder="搜索行业标签..."
        class="w-full pl-10 pr-4 py-2 cyber-input text-sm"
        @input="handleSearch"
      />
      <button
        v-if="searchQuery"
        @click="clearSearch"
        class="absolute right-3 top-1/2 transform -translate-y-1/2 "
      >
        <X class="w-4 h-4" />
      </button>
    </div>

    <!-- 选中的标签显示 -->
    <div v-if="selectedTags.length > 0" class="mb-6">
      <div class="flex items-center justify-between mb-4">
        <span class=" text-base font-medium">✅ 已选择 ({{ selectedTags.length }})</span>
        <button
          @click="clearAllTags"
          class="text-electric-500 hover:text-electric-400 text-sm font-medium transition-colors"
        >
          清空所有
        </button>
      </div>
      <div class="flex flex-wrap gap-3 max-h-32 overflow-y-auto scrollbar-thin">
        <span
          v-for="tag in selectedTags"
          :key="tag"
          class="inline-flex items-center px-3 py-2 bg-electric-500/20 text-electric-300 rounded-full text-sm font-medium whitespace-nowrap"
        >
          {{ tag }}
          <button
            @click="removeTag(tag)"
            class="ml-2 hover:text-electric-100 transition-colors"
          >
            <X class="w-4 h-4" />
          </button>
        </span>
      </div>
    </div>

    <!-- 快速选择热门标签 -->
    <div v-if="!searchQuery && showPopular" class="mb-6">
      <h4 class=" text-base font-medium mb-4">🔥 热门标签</h4>
      <div class="flex flex-wrap gap-3">
        <button
          v-for="tag in popularTags"
          :key="tag"
          @click="toggleTag(tag)"
          :class="[
            'px-4 py-2 rounded-full text-sm font-medium transition-all duration-200 whitespace-nowrap',
            selectedTags.includes(tag)
              ? 'bg-electric-500  shadow-lg shadow-electric-500/25'
              : 'bg-tech-blue-500/20 hover:bg-tech-blue-500/40 text-tech-blue-300 hover:shadow-md'
          ]"
        >
          {{ tag }}
        </button>
      </div>
    </div>

    <!-- 标签列表 -->
    <div class="space-y-4 max-h-96 overflow-y-auto scrollbar-thin">
      <!-- 搜索结果 -->
      <div v-if="searchQuery && searchResults.length > 0">
        <h4 class=" text-base font-medium mb-4">🔍 搜索结果</h4>
        <div class="space-y-3">
          <div
            v-for="result in searchResults"
            :key="`search-${result.tag}`"
            class="flex items-center justify-between p-3 bg-white/5 rounded-lg hover:bg-white/10 transition-all duration-200"
          >
            <div class="flex-1 min-w-0">
              <span class=" text-sm font-medium">{{ result.tag }}</span>
              <span v-if="result.level === 2" class=" text-xs ml-2 block">
                所属: {{ result.parent }}
              </span>
            </div>
            <button
              @click="toggleTag(result.tag)"
              :class="[
                'px-3 py-2 rounded-lg text-sm font-medium transition-all duration-200 whitespace-nowrap ml-3',
                selectedTags.includes(result.tag)
                  ? 'bg-electric-500  shadow-lg'
                  : 'bg-tech-blue-500/20 hover:bg-tech-blue-500/40 text-tech-blue-300'
              ]"
            >
              {{ selectedTags.includes(result.tag) ? '已选' : '选择' }}
            </button>
          </div>
        </div>
      </div>

      <!-- 分级标签显示 -->
      <div v-else-if="!searchQuery">
        <div
          v-for="(level2Tags, level1) in filteredTags"
          :key="level1"
          class="mb-6"
        >
          <div class="flex items-center justify-between mb-4 p-2">
            <button
              @click="toggleCategory(level1)"
              class="flex items-center space-x-3 hover:text-electric-400 transition-all duration-200 group"
            >
              <ChevronDown
                :class="[
                  'w-5 h-5 transition-transform duration-200',
                  expandedCategories.includes(level1) ? '' : '-rotate-90'
                ]"
              />
              <span class="font-semibold bg-black/10">{{ level1 }}</span>
              <span class="text-sm bg-white/10 px-2 py-1 rounded-full">{{ level2Tags.length }}</span>
            </button>
            <button
              @click="selectAllInCategory(level1, level2Tags)"
              class="text-electric-500 hover:text-electric-400 text-sm font-medium transition-colors px-2 py-1 rounded"
            >
              {{ getSelectedInCategory(level2Tags) === level2Tags.length ? '取消全选' : '全选' }}
            </button>
          </div>
          <div
            v-show="expandedCategories.includes(level1)"
            class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3 ml-4 p-3 bg-white/2 rounded-lg"
          >
            <button
              v-for="tag in level2Tags"
              :key="tag"
              @click="toggleTag(tag)"
              :class="[
                'px-3 py-2 rounded-lg text-sm text-left transition-all duration-200 font-medium whitespace-nowrap overflow-hidden text-ellipsis',
                selectedTags.includes(tag)
                  ? 'bg-electric-500  shadow-lg transform scale-105'
                  : 'bg-white/5 hover:bg-white/15 hover:shadow-md'
              ]"
              :title="tag"
            >
              {{ tag }}
            </button>
          </div>
        </div>
      </div>

      <!-- 无搜索结果 -->
      <div v-else-if="searchQuery && searchResults.length === 0" class="text-center py-12">
        <Search class="w-16 h-16 mx-auto mb-4 " />
        <p class=" text-base">未找到相关标签</p>
        <p class=" text-sm mt-2">请尝试其他关键词</p>
      </div>
    </div>
  </div>
</template>

<script>
import { Search, X, ChevronDown } from 'lucide-vue-next'

export default {
  name: 'TagSelector',
  components: {
    Search,
    X,
    ChevronDown
  },
  props: {
    modelValue: {
      type: Array,
      default: () => []
    },
    showPopular: {
      type: Boolean,
      default: true
    },
    maxSelection: {
      type: Number,
      default: 10
    },
    allTags: {
      type: Object,
      default: () => ({})
    },
    allPopularTags: {
      type: Array,
      default: () => []
    }
  },
  emits: ['update:modelValue', 'change'],
  data() {
    return {
      searchQuery: '',
      searchResults: [],
      expandedCategories: [],
    }
  },
  computed: {
    selectedTags: {
      get() {
        return this.modelValue
      },
      set(value) {
        this.$emit('update:modelValue', value)
        this.$emit('change', value)
      }
    },
    filteredTags() {
      // 直接用props传入的allTags
      return this.allTags
    },
    popularTags() {
      // 直接用props传入的allPopularTags
      return this.allPopularTags
    }
  },
  mounted() {
    // 不再主动loadTags，数据由父组件传入
    if (this.allTags && Object.keys(this.allTags).length > 0) {
      this.expandedCategories = [Object.keys(this.allTags)[0]]
    }
  },
  methods: {
    // loadTags方法移除，数据由props传入
    
    handleSearch() {
      if (this.searchQuery.trim()) {
        const query = this.searchQuery.toLowerCase()
        const results = []
        
        // 搜索所有级别的标签
        Object.entries(this.allTags).forEach(([level1, level2Tags]) => {
          level2Tags.forEach(tag => {
            if (tag.toLowerCase().includes(query)) {
              results.push({
                tag: tag,
                parent: level1,
                level: 2
              })
            }
          })
        })
        
        this.searchResults = results.slice(0, 15)
      } else {
        this.searchResults = []
      }
    },
    
    clearSearch() {
      this.searchQuery = ''
      this.searchResults = []
    },
    
    toggleTag(tag) {
      const index = this.selectedTags.indexOf(tag)
      const newSelection = [...this.selectedTags]
      
      if (index > -1) {
        newSelection.splice(index, 1)
      } else {
        if (newSelection.length < this.maxSelection) {
          newSelection.push(tag)
        } else {
          this.$emit('max-selection-reached', this.maxSelection)
          return
        }
      }
      
      this.selectedTags = newSelection
    },
    
    removeTag(tag) {
      const newSelection = this.selectedTags.filter(t => t !== tag)
      this.selectedTags = newSelection
    },
    
    clearAllTags() {
      this.selectedTags = []
    },
    
    toggleCategory(category) {
      const index = this.expandedCategories.indexOf(category)
      if (index > -1) {
        this.expandedCategories.splice(index, 1)
      } else {
        this.expandedCategories.push(category)
      }
    },
    
    selectAllInCategory(category, tags) {
      const selectedCount = this.getSelectedInCategory(tags)
      const newSelection = [...this.selectedTags]
      
      if (selectedCount === tags.length) {
        // 取消全选
        tags.forEach(tag => {
          const index = newSelection.indexOf(tag)
          if (index > -1) {
            newSelection.splice(index, 1)
          }
        })
      } else {
        // 全选
        tags.forEach(tag => {
          if (!newSelection.includes(tag) && newSelection.length < this.maxSelection) {
            newSelection.push(tag)
          }
        })
      }
      
      this.selectedTags = newSelection
    },
    
    getSelectedInCategory(tags) {
      return tags.filter(tag => this.selectedTags.includes(tag)).length
    }
  }
}
</script>

<style scoped>
.tag-selector {
  color: #fff;
}

.scrollbar-thin::-webkit-scrollbar {
  width: 6px;
}

.scrollbar-thin::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 3px;
}

.scrollbar-thin::-webkit-scrollbar-thumb {
  background: rgba(0, 255, 255, 0.4);
  border-radius: 3px;
}

.scrollbar-thin::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 255, 255, 0.6);
}

/* 标签按钮悬停效果 */
.tag-selector button {
  min-height: 32px;
  line-height: 1.2;
}

.tag-selector button:hover {
  transform: translateY(-1px);
}

.tag-selector button:active {
  transform: translateY(0);
}

/* 确保长标签文本不会溢出 */
.tag-selector .text-ellipsis {
  max-width: 100%;
  display: block;
}
</style> 
<style>
/* 浅色模式下标签chip、按钮等高对比度适配 */
.theme-light .tag-selector .bg-electric-500\/20,
.theme-light .tag-selector .bg-tech-blue-500\/20 {
  background: #e0f7fa !important;
  color: #007a8a !important;
  border: 1px solid #b2e6f7 !important;
  box-shadow: 0 1px 4px #b2e6f733;
}
.theme-light .tag-selector .text-electric-300 {
  color: #0097a7 !important;
}
.theme-light .tag-selector .text-white,
.theme-light .tag-selector .text-white\/70,
.theme-light .tag-selector .text-white\/80,
.theme-light .tag-selector .text-white\/50 {
  color: #222 !important;
}
.theme-light .tag-selector .text-electric-500 {
  color: #00b8d9 !important;
}
.theme-light .tag-selector .cyber-input {
  background: #f7fafc !important;
  color: #222 !important;
  border-color: #b2e6f7 !important;
}
</style>
